import React, { useState, useRef } from 'react'
import './index.css'
import { Form, Input, Button, Space, Message } from '@arco-design/web-react'
import Logo from '@assets/images/logo.png'
import { withRouter } from 'react-router-dom'
import { registerApi } from '@@/src/api/chat'

function Register(props) {
  const formRef = useRef()
  const [form] = Form.useForm()

  const [loading, setLoading] = useState(false)

  // 注册
  const handleRegister = (params) => {
    setLoading(true)
    registerApi(params)
      .then((res) => {
        const { code, msg } = res
        if (code === 0) {
          Message.success('注册成功！')
          props.history.push('/login')
        } else {
          Message.error('注册失败：' + msg)
          form.setFieldsValue({ username: '', password: '', password2: '' })
        }
      })
      .catch((err) => {
        console.log(err)
        console.log('props', props)
        form.setFieldsValue({ username: '', password: '', password2: '' })
      })
      .finally(() => {
        setLoading(false)
      })
  }

  // 注册
  function onSubmitClick() {
    formRef.current.validate().then((values) => {
      handleRegister({ ...values })
    })
  }

  return (
    <div className={'register-form-wrapper'}>
      {/* 左边 */}
      <div className='register-form-left'></div>
      {/* 右边 */}
      <div className='register-form-right'>
        <img src={Logo} alt='logo' className='register-logo' />
        {/* 表单 */}
        <Form
          form={form}
          className={['register-form']}
          layout='vertical'
          ref={formRef}
          autoComplete='off'
          validateMessages={{
            // required: (_, { label }) => `请填写 ${label}`,
            required: (_, { label }) => `请填写`,
            string: {
              minLength: `长度要大于#{minLength}`,
              maxLength: `长度要小于#{maxLength}`,
              match: `必须由英文字母开头，且只包含英文字母、数字、下划线`,
            },
            number: {
              min: `最小值为 #{min}`,
              max: `最大值为 #{max}`,
            },
          }}
        >
          <div className={'register-form-title'}>注册</div>
          {/* <div className={['register-form-sub-title']}>赶快注册体验吧~</div> */}
          <Form.Item
            // label='用户名'
            field='username'
            required
            rules={[
              {
                type: 'string',
                required: true,
                match: /^[a-zA-Z][a-zA-Z0-9_]*$/,
                minLength: 6,
                maxLength: 16,
              },
            ]}
          >
            <Input
              size={'large'}
              prefix={'用户名'}
              placeholder={'用户名'}
              autoComplete={false}
              onPressEnter={onSubmitClick}
            />
          </Form.Item>
          <Form.Item
            field='realName'
            required
            rules={[{ type: 'string', required: true, minLength: 1, maxLength: 16 }]}
          >
            <Input size={'large'} prefix={'昵称'} placeholder={'昵称'} onPressEnter={onSubmitClick} />
          </Form.Item>
          <Form.Item field='password' rules={[{ type: 'string', required: true, minLength: 6, maxLength: 16 }]}>
            <Input.Password size={'large'} prefix={'密码'} placeholder={'密码'} onPressEnter={onSubmitClick} />
          </Form.Item>
          <Form.Item
            field='password2'
            rules={[
              {
                type: 'string',
                validator: (v, cb) => {
                  if (!v) {
                    return cb('请输入确认密码')
                  } else if (form.getFieldValue('password') !== v) {
                    return cb('确认密码必须和密码一致')
                  }
                  cb(null)
                },
              },
            ]}
          >
            <Input.Password size={'large'} prefix={'确认密码'} placeholder={'确认密码'} onPressEnter={onSubmitClick} />
          </Form.Item>
          <Space size={16} direction='vertical'>
            <Button size={'large'} type='primary' long onClick={onSubmitClick} loading={loading}>
              注册
            </Button>
            <Button size={'large'} type='text' long onClick={() => props.history.replace('/login')}>
              已有账号，去登录
            </Button>
          </Space>
        </Form>
      </div>
    </div>
  )
}

export default withRouter(Register)
